package message

import (
	"fmt"
	"gm/lib"
	"log"
	"mime"
	"strings"
	"time"

	"gopkg.in/gomail.v2"
)

//Email the message
type Email struct {
}

// Send email
func (e *Email) Send(subject, content, users string, attachFilePaths []string, attachFileNames []string, late int64, sendInOne bool) {
	m := gomail.NewMessage()
	m.SetAddressHeader("From", from, username) // 发件人
	m.SetHeader("Subject", subject)            // 主题
	m.SetBody("text/html", content)            // 正文
	// 发送邮件服务器、端口、发件人账号、发件人密码
	d := gomail.NewPlainDialer(smtp, port, username, password)

	if len(attachFilePaths) > 0 { //附件设置
		if len(attachFilePaths) != len(attachFileNames) {
			log.Panic("attach filepath's length is not equal to filename's length\n")
			return
		}
		for i, v := range attachFilePaths {
			attachFileName := attachFileNames[i]
			if !lib.Exist(v) {
				log.Panicf("attach file is not exist: %s \n", v)
				return
			}
			m.Attach(v,
				gomail.Rename(attachFileName),
				gomail.SetHeader(map[string][]string{ //解决附件名乱码
					"Content-Disposition": []string{
						fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", attachFileName)),
					},
				}),
			)
		}
	}

	if late > 0 { //延时发送
		log.Printf("sleep for %d millisecond! \n", late)
		time.Sleep(time.Duration(late) * time.Millisecond)
	}

	us := strings.Split(users, ",")
	if sendInOne { //用一封邮件发给所有人
		var toUsers []string
		for _, u := range us {
			toUsers = append(toUsers, m.FormatAddress(u, u))
		}
		log.Printf("send email to user %s \n", toUsers)
		m.SetHeader("To", toUsers...) // 收件人
		if err := d.DialAndSend(m); err != nil {
			log.Printf("send email to user %s fail, err -> %s \n", toUsers, err)
		} else {
			log.Printf("send mail to %s success! \n", toUsers)
		}
	} else {
		for _, u := range us {
			log.Printf("send email to user %s \n", u)
			m.SetHeader("To", m.FormatAddress(u, u)) // 收件人
			if err := d.DialAndSend(m); err != nil {
				log.Printf("send email to user %s fail, err -> %s \n", u, err)
			} else {
				log.Printf("send mail to %s success! \n", u)
			}
		}
	}

}
